<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="标题">
          <a-input placeholder="请输入标题" v-decorator="['title', validatorRules.title]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
          <a-input placeholder="请输入备注" v-decorator="['memo', validatorRules.memo]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图片">
          <a-upload
            name="file"
            listType="picture-card"
            :fileList="fileList"
            class="avatar-uploader"
            action="/resource-api//resource/image/uploadImage"
            :beforeUpload="beforeUpload"
            @change="handleChange"
            :remove="removeFile"
            v-decorator="['picUrl', { rules: [{ required: true, message: '请上传图片' }] }]"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">Upload</div>
            </div>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handlePicCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </a-upload>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input-number :min="0" v-decorator="['sort', validatorRules.sort]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
          <a-select
            @change="changeType"
            placeholder="类型"
            v-decorator="['status', validatorRules.status]"
          >
            <a-select-option value="1">开启</a-select-option>
            <a-select-option value="2">关闭</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            @change="changeType"
            placeholder="类型"
            v-decorator="['type', { rules: [{ required: true, message: '请选择类型' }] }]"
          >
            <a-select-option value="1">商店</a-select-option>
            <a-select-option value="2">商品</a-select-option>
            <a-select-option value="3">外部链接</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="商店" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="type == 1">
          <a-select
            showSearch
            :defaultActiveFirstOption="false"
            :showArrow="false"
            :filterOption="false"
            placeholder="请选择商店"
            @search="handleShopSearch"
            @change="handleShopChange"
            notFoundContent="null"
            v-decorator="['url', { rules: [{ required: this.type == 1, message: '请选择商店' }] }]"
          >
            <a-select-option value="10">正在加载</a-select-option>
            <a-select-option v-for="d in shopList" :key="d.id">{{ d.shopName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="商品列表" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="type == 2">
          <a-select
            showSearch
            :defaultActiveFirstOption="false"
            :showArrow="false"
            :filterOption="false"
            placeholder="请选择商品"
            @search="handleGoodsSearch"
            @change="handleGoodsChange"
            notFoundContent="null"
            v-decorator="['url', { rules: [{ required: this.type == 2, message: '请选择类型' }] }]"
          >
            <a-select-option value="10">正在加载</a-select-option>
            <a-select-option v-for="d in spuList" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="跳转链接" v-show="type == 3">
          <a-input
            placeholder="请输入跳转链接"
            v-decorator="['url', { rules: [{ required: this.type == 3, message: '请选择类型' }] }]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'

export default {
  name: 'bannerModal',
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      title: '操作',
      uploadDisable: false,
      visible: false,
      loading: false,
      type: 1,
      imageUrl: '',
      model: {},
      fileList: [],
      spuList: [],
      shopList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        deleted: { rules: [{ required: true, message: '请输入是否删除!' }] },
        memo: { rules: [{ required: true, message: '请输入备注!' }] },
        picUrl: { rules: [{ required: true, message: '请输入跳转链接!' }] },
        sort: { rules: [{ required: true, message: '请输入排序!' }] },
        status: { rules: [{ required: true, message: '请输入状态!' }] },
        title: { rules: [{ required: true, message: '请输入标题!' }] },
        url: { rules: [{ required: this.type == 3, message: '请输入跳转链接!' }] }
      },
      url: {
        add: '/promotion-api/admins/banner/add',
        edit: '/promotion-api/admins/banner/update'
      }
    }
  },
  created() {},
  onactived() {
    this.uploadDisable = true
    this.fileList = []
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      debugger
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'type', 'memo', 'picUrl', 'sort', 'status', 'title', 'url'))
        //时间格式化
      })
      this.fileList=[{name: this.form.model.picUrl}]

    },
    close() {
      this.fileList = []
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      debugger
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          //时间格式化

          console.log('1')
          formData.type = parseInt(formData.type)
          formData.status = parseInt(formData.status)
          console.log('2')
          console.log(this.fileList)
          if (this.fileList.length > 0) {
            console.log('3ss')

            formData.picUrl = this.fileList[0].name
            console.log('3121')
          }
          console.log('3sd')

          httpAction(httpurl, formData, method)
            .then(res => {
              console.log('4')

              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              console.log('5')

              that.confirmLoading = false
              that.close()
            })
        }
      })
    },

    changeType(value) {
      if (value == 1) {
        this.type = 1
      }
      if (value == 2) {
        this.type = 2
      }
      if (value == 3) {
        this.type = 3
      }
      this.form.validateFields(['url'], { force: true })
    },
    handleGoodsChange(value) {},
    handleGoodsSearch(value) {
      let params = { goodsName: value + '*' }
      getAction('/shop-api/shop/web/shopList', params).then(res => {
        if (res.success) {
          this.shopList = res.result.records
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
    },
    handleShopChange(value) {},
    handleShopSearch(value) {
      let params = { shopName: value + '*' }
      getAction('/shop-api/shop/web/shopList', params).then(res => {
        if (res.success) {
          this.shopList = res.result.records
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
    },
    handlePicCancel() {
      this.previewVisible = false
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    removeFile(value) {
      if (value) {
        this.uploadDisable = false
      }
    },
    handleChange(info) {
      debugger
      if (info.file.status == 'done') {
        debugger
        this.form.setFieldsValue('picUrl', info.file.response.result.imageUri)
        this.uploadDisable = true
      }
      this.fileList = info.fileList
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJPG && isLt2M
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style lang="less" scoped></style>
